package com.whale.cloud.util.rest.condition;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.whale.cloud.exception.CommonException;
import com.whale.cloud.util.StringUtils;
import com.whale.cloud.util.rest.dataengine.LogicExpression;
import com.whale.cloud.util.rest.schema.Column;
import com.whale.cloud.util.rest.schema.Function;
import lombok.extern.log4j.Log4j2;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/** Created by paco on 5/6/2017. */
@Log4j2
public class MysqlCondition implements Condition {
  private Function masterTable; //主数据表
  private QueryUtil qu;
  private CreateUtil cu;
  private UpdateUtil uu;

  private MysqlCondition() {
    qu = new QueryUtil();
    cu = new CreateUtil();
    uu = new UpdateUtil();
  }

  /**
   * @param masterTable 主数据表
   * @return
   */
  public static MysqlCondition getInstance(Function masterTable) {
    MysqlCondition condition = new MysqlCondition();
    condition.masterTable = masterTable;
    return condition;
  }

  private void setSearchColumns(List<Column> columns) {
    qu.setSearchColumns(columns);
  }

  public void setLe(LogicExpression le) {
    qu.setLe(le);
  }

  @Override
  public Object[] getQueryDataParam() {
    return qu.dataParam.toArray(new Object[qu.dataParam.size()]);
  }

  @Override
  public void setOrderBy(JSONArray orderby) {
    qu.setOrderBy(orderby);
  }

  @Override
  public void setPage(int beginIndex, int endIndex) {
    qu.setPage(beginIndex, endIndex);
  }

  @Override
  public void setCondition(LogicExpression le) {
    setLe(le);
  }

  @Override
  public String getCreateSql(JSONObject dataParam, List<Column> userColumns) {
    return cu.getSql(dataParam, userColumns);
  }

  @Override
  public Object[] getCreateDataParam() {
    return cu.insertParam.toArray(new Object[qu.dataParam.size()]);
  }

  @Override
  public String getCountSql() {
    return qu.getCountSql();
  }

  @Override
  public String getQuerySql(List<Column> c) {
    setSearchColumns(c);
    return qu.getQuerySql();
  }

  @Override
  public String getUpdateSql(JSONObject dataParam, List<Column> userColumns) {
    return uu.getSql(dataParam, userColumns);
  }

  @Override
  public Object[] getUpdateDataParam() {
    return uu.modifyParam.toArray(new Object[qu.dataParam.size()]);
  }

  @Override
  public String getDeleteSql(JSONObject dataParam) {
    return null;
  }

  private class QueryUtil {
    private LogicExpression le; //条件表达式
    private List<Column> columns; //要查询的字段集
    private List<Object> dataParam = new ArrayList<>(); //参数集

    private StringBuffer columnSb = new StringBuffer(); //查询字段语句
    private StringBuffer foreignTableSb = new StringBuffer(); //关联表语句
    private StringBuffer conditionSb = new StringBuffer(); //条件
    private StringBuffer orderBySb = new StringBuffer(); //排序语句
    private int dataBegin; //起始数据
    private int dataNum; //查询数据量

    private List<String> foreignColuns = new ArrayList<>(); //外键关联字段 格式为：column1.column2;column3
    private List<Function> foreignTables = new ArrayList<>();

    private StringBuffer setCondition(LogicExpression le) {
      StringBuffer sqlsb = new StringBuffer();
      if(le==null || le.getAllExpression()==null){
        return null;
      }
      int lecount = le.getAllExpression().size();

      LogicExpression temple = null;
      if (lecount > 0) {
        sqlsb.append("(");

        for (int i = 0; i < lecount; i++) {
          temple = le.getAllExpression().get(i);
          if (sqlsb.length() > 1) {
            sqlsb.append(" ").append(temple.getEl().getCode()).append(" ");
          }
          sqlsb.append(setCondition(temple));
        }
        sqlsb.append(")");
      } else {
        if (sqlsb.length() > 1) {
          sqlsb.append(" ").append(le.getEl().getCode()).append(" ");
        }
        sqlsb.append(setSubCondidtion(le));
      }

      return sqlsb;
    }

    private StringBuffer setSubCondidtion(LogicExpression le) {
      String decorateStr = "";

      String tableTag = masterTable.getDBName();
      String columnTag = le.getColumnDBName();

      String tempColumnValue = le.getValue();
      StringBuffer subsql = new StringBuffer();

      if (StringUtils.isNull(tempColumnValue)) {
        return subsql;
      }
      tempColumnValue = tempColumnValue.trim();
      Pattern pp = Pattern.compile("(?<=^\\s*[\\[\\{])[^\\)\\}]+(?=\\s*[\\]\\}]\\s*$)"); //(?<!\\\\)
      Matcher mm = null;

      //region 判断字段名前是否有修饰符
      pp = Pattern.compile("(?<=\\W+)\\w+\\s*[\\[||}]$"); //(?<!\\\\)
      mm = pp.matcher(columnTag);
      if (mm.find()) {
        decorateStr = columnTag;
        columnTag = mm.group();
        decorateStr = decorateStr.replace(columnTag, "");
      }
      //endregion

      //region 字段处理
      disposeForeignColumn(columnTag, tableTag, columnTag);
      //endregion

      if (le.getERelation() == ERelation.range) {
        //region 1、判断是否是范围
        pp = Pattern.compile("(?<=^\\s*[\\[\\{])[^\\]\\}]+(?=[\\]\\}]\\s*$)");
        mm = pp.matcher(tempColumnValue);
        if (mm.find()) {
          String tempValue = mm.group();
          String[] values = tempValue.split("\\s+TO\\s+");
          if (values == null || values.length < 2) {
            return subsql;
          }

          //1、* TO *
          if ("*".equals(values[0].trim()) && "*".equals(values[1].trim())) {
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag).append(" is not null");
            return subsql;
          }

          //2、* TO ~
          if ("*".equals(values[0].trim()) && !"*".equals(values[1].trim())) {
            pp = Pattern.compile("[\\]]\\s*$");
            mm = pp.matcher(tempColumnValue);
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag).append(" <");
            if (mm.find()) {
              subsql.append("= ");
            }
            subsql.append("?");
            dataParam.add(values[1]);
            return subsql;
          }

          //3、~ TO *
          if (!"*".equals(values[0].trim()) && "*".equals(values[1].trim())) {
            pp = Pattern.compile("^\\s*[\\[]");
            mm = pp.matcher(tempColumnValue);
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag).append(" >");
            if (mm.find()) {
              subsql.append("= ");
            }
            subsql.append("?");
            dataParam.add(values[0]);
            return subsql;
          }
          //4、~ TO ~
          if (!"*".equals(values[0].trim()) && !"*".equals(values[1].trim())) {
            pp = Pattern.compile("^\\s*[\\[]");
            mm = pp.matcher(tempColumnValue);

            subsql.append(" (");
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag).append(" >");
            if (mm.find()) {
              subsql.append("= ");
            }
            subsql.append("?");
            dataParam.add(values[0]);

            pp = Pattern.compile("[\\]]\\s*$");
            mm = pp.matcher(tempColumnValue);
            subsql.append(" and ");
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag).append(" <");
            if (mm.find()) {
              subsql.append("= ");
            }
            subsql.append("?");
            dataParam.add(values[1]);
            subsql.append(" )");
            return subsql;
          }
        }
        //endregion

        //region 2、可选值处理 eg：张三 AND 李四 AND 王五 或者 eg：张三 OR 李四 OR 王五
        //判断是and 还是 or
        pp = Pattern.compile("\\s+AND\\s+"); //(?<!\\\\)
        mm = pp.matcher(tempColumnValue);

        String[] values = null;
        String tempValue = null;
        int vlength = 0;
        String logicStr = "OR";
        if (mm.find()) {
          logicStr = "AND";
        }
        //修改模糊查询 或影响范围查询 ！！！！！
//        values = tempColumnValue.split("(\\s+(AND|OR)\\s+)|(\\s+)");
        values = tempColumnValue.split("(\\s+(AND|OR)\\s+)");
        vlength = values.length;
        if (vlength > 1) {
          subsql.append("(");
        }
        for (int i = 0; i < vlength; i++) {
          tempValue = values[i];
          if (StringUtils.isNull(tempValue)) {
            continue;
            //log.error("column value mast not null:"+tempColumnValue);
            //throw new CommonException("-60","字段："+columnTag+" 查询值不能为空");
          }

          if (i > 0) {
            subsql.append(" ").append(logicStr).append(" ");
          }
          //如果值前后有星号，则用模糊查询
          pp = Pattern.compile("^\\s*\\*|\\*\\s*$"); //(?<!\\\\)
          mm = pp.matcher(tempValue);
          if (mm.find()) {
            tempValue = tempValue.replaceAll("^\\s*\\*|\\*\\s*$", "%");
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag);
            if (StringUtils.isNotNull(decorateStr) && "NOT".equalsIgnoreCase(decorateStr)) {
              subsql.append(" not");
            }
            subsql.append(" like ?");
            dataParam.add(tempValue);
          } else {
            if (StringUtils.isNotNull(tableTag)) {
              subsql.append(tableTag).append(".");
            }
            subsql.append(columnTag);
            if (StringUtils.isNotNull(decorateStr) && "NOT".equalsIgnoreCase(decorateStr)) {
              subsql.append(" <> ?");
            } else {
              subsql.append(" = ?");
            }

            dataParam.add(tempValue);
          }
        }

        if (vlength > 1) {
          subsql.append(")");
        }

        //endregion
      } else {
        if (StringUtils.isNotNull(tableTag)) {
          subsql.append(tableTag).append(".");
        }
        subsql.append(tableTag).append(le.getERelation().getCode()).append(tempColumnValue);
      }

      return subsql;
    }

    private void setSearchColumns(List<Column> columns) {
      columnSb = new StringBuffer();
      if (columns == null || columns.size() <= 0) {
        return;
      }

      columnSb.append(masterTable.getDBName()).append(".").append(masterTable.getPK().getDb_name());
      int clength = columns.size();
      Column c = null;

      String columnTag = null;
      String tableTag = null;
      for (int i = 0; i < clength; i++) {
        c = columns.get(i);
        if (c == null) {
          continue;
        }

        if (c.getId() == masterTable.getPK().getId()) {
          continue;
        }

        //region xdl 忽略不处理
        if(c.getVoluationType()==EVoluationType.ignore){
          continue;
        }
        //endregion

        tableTag = masterTable.getDBName();
        columnTag = c.getDb_name();

        //region 判断是否虚拟字段
        disposeForeignColumn(c, tableTag, columnTag);
        //endregion

        columnSb.append(",");
        if (StringUtils.isNotNull(tableTag)) {
          columnSb.append(tableTag).append(".");
        }
        columnSb.append(columnTag);
      }
    }

    private void setLe(LogicExpression le) {
      this.le = le;
      conditionSb = setCondition(le);
    }

    private JSONObject disposeForeignColumn(String columnDBName, String tableTag, String columnTag) {
      Column tempColumn = masterTable.getColumnByDBName(columnDBName);
      if (tempColumn == null) {
        log.error("column:" + columnTag + " not in table:" + masterTable.getDBName());
        throw new CommonException("-50", "字段不能为空");
      }
      log.debug("-----disposeForeignColumn:"+columnDBName+","+tableTag+","+columnTag);
      return disposeForeignColumn(tempColumn, tableTag, columnTag);
    }

    private JSONObject disposeForeignColumn(Column c, String tableTag, String columnTag) {
      Column tempColumn = c;
      Function tempTable = masterTable;

      tableTag = masterTable.getDBName();
      columnTag = c.getDb_name();
      log.debug("-------disposeForeignColumn:"+tableTag+","+columnTag);

      //region 判断是否虚拟字段
      if (c.getDb_name().indexOf(";") > -1) {
        String virtualName = null;

        String[] columnsarray = c.getDb_name().split(".|;");

        int index = -1;
        int clength = columnsarray.length;
        for (int i = 0; i < clength - 1; i++) {
          columnTag = columnsarray[i];
          tempColumn = tempTable.getColumnByDBName(columnTag.trim());
          if (tempColumn == null) {
            log.error("foreign column:" + columnTag + " is not in table:" + tempTable.getDBName());
            throw new CommonException("-50", "字段：" + columnTag + " 维护有误");
          }
          tempTable = tempColumn.getForeign_table();

          if (tempTable == null) {
            log.error("column:" + columnTag + " foreign table is null");
            throw new CommonException("-70", "字段：" + tempColumn.getShow_name() + "未维护外键关联表");
          }
          if (StringUtils.isNull(virtualName)) {
            virtualName = tempColumn.getDb_name();
          } else {
            virtualName += "." + tempColumn.getDb_name();
          }

          index = foreignColuns.indexOf(virtualName);
          if (index > -1) {
            tableTag = "t" + index;
          } else {
            tableTag = "t" + foreignColuns.size();
            foreignColuns.add(virtualName);
            if (tempTable.getPK() == null) {
              log.error("table:" + tempTable.getDBName() + " not pk column");
              throw new CommonException("-70", "表：" + tempTable.getShowName() + " 未维护主键");
            }
            foreignTableSb
                .append(" left join ")
                .append(tempTable.getRealFunctionName())
                .append(" ")
                .append(tableTag);
            foreignTableSb
                .append(" on ")
                .append(masterTable.getDBName())
                .append(".")
                .append(tempColumn.getDb_name())
                .append("=")
                .append(tableTag)
                .append(".")
                .append(tempTable.getPK().getDb_name());
          }
        }

        //如果是虚拟字段，则不需要表名
        columnTag = columnsarray[clength - 1];
        tempColumn = tempTable.getColumnByDBName(columnTag.trim());
        if (tempColumn == null) {
          log.error("foreign column:" + columnTag + " is not in table:" + tempTable.getDBName());
          throw new CommonException("-50", "字段：" + columnTag + " 维护有误");
        }
        if (tempColumn != null && tempColumn.getVoluationType() == EVoluationType.ignore) {
          columnTag =
              columnTag.replaceAll("(?<=\\()" + tempTable.getDBName() + "(?=\\.)", tableTag);
          tableTag = "";
        }
      }
      JSONObject result=new JSONObject();
      result.put("tableTag",tableTag);
      result.put("columnTag",columnTag);
      return result;
    }

    private void setOrderBy(JSONArray orderby) {
      orderBySb = new StringBuffer();

      if (orderby == null || orderby.size() <= 0) {
        return;
      }
      orderBySb.append(" order by ");
      int oblength = orderby.size();
      String columnDBName = "";
      boolean isAsc = false;
      JSONObject orderByInfo = null;
      String tableTag = null;
      String columnTag = null;
      for (int i = 0; i < oblength; i++) {
        orderByInfo = orderby.getJSONObject(i);
        columnDBName = orderByInfo.getString("column");

        JSONObject foreignColumn=disposeForeignColumn(columnDBName, tableTag, columnTag);
        if(foreignColumn.containsKey("tableTag")) tableTag=foreignColumn.getString("tableTag");
        if(foreignColumn.containsKey("columnTag")) columnTag=foreignColumn.getString("columnTag");
        log.debug("----setOrderBy:"+tableTag+","+columnTag);
        isAsc = "Y".equalsIgnoreCase(orderByInfo.getString("is_asc"));

        if (i > 0) {
          orderBySb.append(",");
        }
        if (StringUtils.isNotNull(tableTag)) {
          orderBySb.append(tableTag).append(".");
        }
        orderBySb.append(columnTag);
        if (isAsc) {
          orderBySb.append(" asc");
        } else {
          orderBySb.append(" desc");
        }
      }
      log.debug("------order by :"+orderBySb.toString());
    }

    private void setPage(int beginIndex, int endIndex) {
      if (beginIndex < 0) {
        beginIndex = 0;
      }
      this.dataBegin = beginIndex;

      if (endIndex <= 0) {
        endIndex = 10;
      }
      this.dataNum = endIndex;
    }

    private String getCountSql() {
      StringBuffer countSql =
          new StringBuffer("select count(1) from ").append(masterTable.getRealFunctionName());
      countSql.append(" ").append(masterTable.getDBName());
      if (conditionSb != null && conditionSb.length() > 0) {
        countSql.append(" where ").append(conditionSb);
      }

      return countSql.toString();
    }

    private String getQuerySql() {
      StringBuffer querySql = new StringBuffer();
      querySql.append("select ").append(columnSb);
      querySql
          .append(" from ")
          .append(masterTable.getRealFunctionName())
          .append(" ")
          .append(masterTable.getDBName());
      if (foreignTableSb != null && foreignTableSb.length() > 0) {
        querySql.append(" ").append(foreignTableSb);
      }
      if (conditionSb != null && conditionSb.length() > 0) {
        querySql.append(" where ").append(conditionSb);
      }
      if (orderBySb != null && orderBySb.length() > 0) {
        querySql.append(" ").append(orderBySb);
      }

      if (dataBegin > 0 || dataNum > 0) {
        querySql.append(" limit ").append(dataBegin).append(",").append(dataNum);
      }

      return querySql.toString();
    }
  }

  private class CreateUtil {
    private List<Object> insertParam = new ArrayList<>(); //参数集

    private String getSql(JSONObject dataParam, List<Column> userColumns) {
      if (dataParam == null || dataParam.isEmpty()) {
        log.error("create param is null");
        throw new CommonException("-80", "请维护需要创建的数据");
      }

      JSONObject createData = dataParam.getJSONObject("master_object");
      if (createData == null || createData.isEmpty()) {
        log.error("master_object is null param:" + dataParam);
        throw new CommonException("-80", "请维护需要创建的数据");
      }

      if (userColumns == null || userColumns.size() <= 0) {
        log.error("create columns is null param:" + dataParam);
        throw new CommonException("-80", "请维护需要创建的字段");
      }

      StringBuffer createSql = new StringBuffer(); //保存创建字段
      StringBuffer valueSql = new StringBuffer(); //保存创建时需要的值
      Object objValue = null;
      String tempValue = null;

      int clength = userColumns.size();
      Column tempColumn = null;
      for (int i = 0; i < clength; i++) {
        tempValue = "?";
        tempColumn = userColumns.get(i);
        if (tempColumn == null) {
          log.error("create user columns is null");
          throw new CommonException("-50", "要创建数据的字段不能为空");
        }

        //如果传入的新增数据中即不包含，也没有默认值，且可为空时，不新增当前字段
        if (!createData.containsKey(tempColumn.getDb_name().toLowerCase())
            && !createData.containsKey(tempColumn.getDb_name().toUpperCase())
            && StringUtils.isNull(tempColumn.getDefaultValue())
            && tempColumn.isNullable()) {
          continue;
        }
        if (tempColumn.getVoluationType() == EVoluationType.pk
            || tempColumn.getVoluationType() == EVoluationType.ignore) {
          continue;
        }

        objValue = createData.get(tempColumn.getDb_name().toLowerCase());
        if (StringUtils.isNull(objValue)) {
          objValue = createData.get(tempColumn.getDb_name().toUpperCase());
        }
        if (tempColumn.getVoluationType() == EVoluationType.createdatetime
            || tempColumn.getVoluationType() == EVoluationType.operatedatetime) {
          tempValue = "now()";
          objValue = tempValue;
        } else if (tempColumn.getVoluationType() == EVoluationType.creater
            || tempColumn.getVoluationType() == EVoluationType.operater) {
          objValue = dataParam.getString("user_id");
        } else if (StringUtils.isNull(objValue)) {
          objValue = tempColumn.getDefaultValue();
        }

        //如果值为空，字段设置为不可为空，则抛异常
        if (!tempColumn.isNullable() && StringUtils.isNull(objValue)) {
          log.error(
              "column:"
                  + masterTable.getDBName()
                  + "."
                  + tempColumn.getDb_name()
                  + " set is not null but value is null");
          throw new CommonException("-80", "请维护：" + tempColumn.getShow_name());
        }

        if (createSql.length() > 0) {
          createSql.append(",");
        }

        if (valueSql.length() > 0) {
          valueSql.append(",");
        }
        if (StringUtils.isNull(objValue)) {
          tempValue = null;
        }
        createSql.append(tempColumn.getDb_name());
        if ("?".equals(tempValue)) {
          insertParam.add(objValue);
//          insertParam.add(String.valueOf(objValue));
        }
        valueSql.append(tempValue);
      }

      StringBuffer insertSql = new StringBuffer("insert into ");
      insertSql.append(masterTable.getRealFunctionName()).append("(");
      insertSql.append(createSql).append(") values(");
      insertSql.append(valueSql).append(")");

      return insertSql.toString();
    }
  }

  private class UpdateUtil {
    private List<Object> modifyParam = new ArrayList<>(); //参数集

    private String getSql(JSONObject dataParam, List<Column> userColumns) {
      if (dataParam == null || dataParam.isEmpty()) {
        log.error("create param is null");
        throw new CommonException("-80", "请维护需要修改的数据");
      }

      JSONObject modifyData = dataParam.getJSONObject("master_object");
      if (modifyData == null || modifyData.isEmpty()) {
        log.error("master_object is null param:" + dataParam);
        throw new CommonException("-80", "请维护需要修改的数据");
      }

      if (userColumns == null || userColumns.size() <= 0) {
        log.error("create columns is null param:" + dataParam);
        throw new CommonException("-80", "请维护需要修改的字段");
      }

      StringBuffer modifySql = new StringBuffer(); //保存修改的字段
      Object objValue = null;
      String tempValue = null;

      int clength = userColumns.size();
      Column tempColumn = null;
      for (int i = 0; i < clength; i++) {
        tempValue = "?";
        tempColumn = userColumns.get(i);
        if (tempColumn == null) {
          log.error("create user columns is null");
          throw new CommonException("-50", "要修改数据的字段不能为空");
        }

        //如果修改的数据中不包含KWY，则不修改
        if (!modifyData.containsKey(tempColumn.getDb_name().toUpperCase())
            && !modifyData.containsKey(tempColumn.getDb_name().toLowerCase())) {
          continue;
        }
        if (tempColumn.getVoluationType() == EVoluationType.pk
            || tempColumn.getVoluationType() == EVoluationType.ignore
            || tempColumn.getVoluationType() == EVoluationType.creater
            || tempColumn.getVoluationType() == EVoluationType.createdatetime
            || tempColumn.getVoluationType() == EVoluationType.no) {
          continue;
        }

        objValue = modifyData.get(tempColumn.getDb_name().toUpperCase());
        if (StringUtils.isNull(objValue)) {
          objValue = modifyData.get(tempColumn.getDb_name().toLowerCase());
        }
        if (tempColumn.getVoluationType() == EVoluationType.createdatetime
            || tempColumn.getVoluationType() == EVoluationType.operatedatetime) {
          tempValue = "now()";
          objValue = tempValue;
        } else if (tempColumn.getVoluationType() == EVoluationType.creater
            || tempColumn.getVoluationType() == EVoluationType.operater) {
          objValue = dataParam.getString("user_id");
        } else if (StringUtils.isNull(objValue)) {
          objValue = tempColumn.getDefaultValue();
        }

        //如果值为空，字段设置为不可为空，则抛异常
        if (!tempColumn.isNullable() && StringUtils.isNull(objValue)) {
          log.error(
              "column:"
                  + masterTable.getDBName()
                  + "."
                  + tempColumn.getDb_name()
                  + " set is not null but value is null");
          throw new CommonException("-80", "请维护：" + tempColumn.getShow_name());
        }

        if (modifySql.length() > 0) {
          modifySql.append(",");
        }
        if (StringUtils.isNull(objValue)) {
          tempValue = null;
        }
        modifySql.append(tempColumn.getDb_name()).append("=").append(tempValue);
        if ("?".equals(tempValue)) {
          modifyParam.add(objValue);
//          modifyParam.add(String.valueOf(objValue));
        }
      }

      long id = modifyData.getLongValue(masterTable.getPK().getDb_name().toLowerCase());
      if (id <= 0) {
        id = modifyData.getLongValue(masterTable.getPK().getDb_name().toUpperCase());
      }
      StringBuffer updateSql = new StringBuffer("update ");
      updateSql.append(masterTable.getRealFunctionName()).append(" set ");
      updateSql.append(modifySql).append(" where ");
      updateSql.append(masterTable.getPK().getDb_name()).append("=?");
      modifyParam.add(id);

      return updateSql.toString();
    }
  }
}
